package com.example.houselease.controller;

import com.example.houselease.ex.ServiceException;
import com.example.houselease.web.JsonResult;
import com.example.houselease.web.ServiceCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传 controller
 * @author xf
 * @version 0.0.1
 * */
@Slf4j
@RestController
@Api(tags = "3. 图片上传管理")
public class UploadController {

    //上传图片存放的地址
//    @Value("${house-lease.dirPath}")
    //先写成自己电脑的保存图片的路径
    private final String dirPath = "G:\\idea\\project\\house-lease\\target\\classes\\static\\avatar";

    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public JsonResult<String> upload(MultipartFile picFile){
        log.debug("{}",picFile);
        //获取原始文件名
        String fileName = picFile.getOriginalFilename();
        //获取文件后缀名 .XXX
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名
        //UUID.randomUUID() 得到的是一个16进制的字符串 唯一标识符
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);

        //创建文件对象
        File dirFile = new File(dirPath);
        //判断文件夹是否存在
        if (!dirFile.exists()){
            dirFile.mkdirs();//创建文件夹
        }
        //定义保存的文件名
        String filePath = dirPath + "/" + fileName;
        try{
            picFile.transferTo(new File(filePath));
        }catch (IOException e){
            String mes = "文件上传失败，请重新尝试";
            log.warn(mes);
            throw new ServiceException(ServiceCode.ERR_UPLOAD,mes);
        }
        String url = "http://localhost:8000/static/avatar/";
        return JsonResult.ok(url+fileName);
    }

    @DeleteMapping("/deletePic")
    @ApiOperation("删除图片")
    void deletePic(String fileName){
        new File(dirPath + "/" + fileName).delete();
    }
}
